package com.xjrsoft.common.runner;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xjrsoft.common.helper.TsHelper;
import com.xjrsoft.common.tsmodel.TsSchemeModel;
import com.xjrsoft.core.tool.utils.CollectionUtil;
import com.xjrsoft.core.tool.utils.SpringUtil;
import com.xjrsoft.core.tool.utils.StringUtil;
import com.xjrsoft.module.taskSchedule.entity.XjrTsProcess;
import com.xjrsoft.module.taskSchedule.entity.XjrTsScheme;
import com.xjrsoft.module.taskSchedule.entity.XjrTsSchemeInfo;
import com.xjrsoft.module.taskSchedule.service.IXjrTsProcessService;
import com.xjrsoft.module.taskSchedule.service.IXjrTsSchemeInfoService;
import com.xjrsoft.module.taskSchedule.service.IXjrTsSchemeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Component
public class TaskSchedulingRunner implements CommandLineRunner {
    @Autowired
    private IXjrTsSchemeInfoService schemeInfoService;
    @Autowired
    private IXjrTsSchemeService schemeService;
    @Autowired
    private IXjrTsProcessService processService;
    @Override
    public void run(String... args) throws Exception {
        List<XjrTsSchemeInfo> schemeInfoList = schemeInfoService.list();
        if (CollectionUtil.isEmpty(schemeInfoList)) {
            return;
        }
        List<String> schemeInfoIdList = schemeInfoList.stream().map(schemeInfo -> schemeInfo.getId()).collect(Collectors.toList());
        List<XjrTsScheme> schemeList = schemeService.list(Wrappers.<XjrTsScheme>query().lambda()
                .in(XjrTsScheme::getSchemeInfoId, schemeInfoIdList)
                .eq(XjrTsScheme::getIsActive, 1));
        List<String> schemeIdList = schemeList.stream().map(XjrTsScheme::getId).collect(Collectors.toList());
        List<XjrTsProcess> processList = processService.list(Wrappers.<XjrTsProcess>query().lambda().in(CollectionUtil.isNotEmpty(schemeIdList),XjrTsProcess::getSchemeId, schemeIdList));
        for (XjrTsProcess process : processList) {
            LocalDateTime endTime = process.getEndType() == 1 ? null : process.getEndTime();
            // 运行结束的定时任务
            Integer state = process.getState();
            // 暂停/运行结束/结束时间超过当前时间 的任务不需要添加
            String processId = process.getId();
            if (state == 4 || state == 3) {
                continue;
            } else if (endTime != null && endTime.compareTo(LocalDateTime.now()) == -1) {
                // 结束时间已过，设置任务为关闭状态
                processService.updateState(processId, 4);
                continue;
            }
            XjrTsScheme scheme = null;
            for (XjrTsScheme item : schemeList) {
                if (StringUtil.equals(item.getId(), process.getSchemeId())) {
                    scheme = item;
                }
            }
            if (scheme == null) {
                continue;
            }
            TsSchemeModel tsSchemeModel = JSONObject.parseObject(scheme.getScheme(), TsSchemeModel.class);
            try {
                TsHelper.addJob(processId, tsSchemeModel);
            } catch (Exception e) {
                log.error("开启任务失败！", e);
            }
            log.info("################  添加定时任务成功！id: " + processId);
        }
    }
}
